Imports System.Web.UI.WebControls.WebParts
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Imports System.Configuration.Provider
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.Util
Imports System.Text
Imports System.Security.Cryptography
Imports System.Configuration
Imports nsDataProvider = KDESolutions.Providers.DataProvider
Public Class DBPersonalizationProvider
    Inherits PersonalizationProvider

    Private Shared DefaultInactiveSinceDate As DateTime = DateTime.MaxValue
    Private Const maxStringLength As Integer = 255
    Private _applicationName As String
    Private _SchemaVersionCheck As Integer
    Private _AppId As String
    Private _TablePrefix As String
    Private _DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString As String

    Public Sub New()
        MyBase.New()
    End Sub

#Region "Public Properties"
    Public Property MyDBType() As String
        Get
            Return _DBType
        End Get
        Set(ByVal value As String)
            _DBType = value
        End Set
    End Property

    Public Overrides Property ApplicationName() As String
        Get
            Return _applicationName
        End Get
        Set(ByVal value As String)
            If String.IsNullOrEmpty(value) Then
                Throw New ArgumentNullException("value")
            End If
            If (value.Length > 255) Then
                Throw New ProviderException("Provider application name too long")
            End If
            _applicationName = value
        End Set
    End Property
#End Region

    Private Function FindSharedState(ByVal path As String, ByVal pageIndex As Integer, ByVal pageSize As Integer, ByRef totalRecords As Integer) As PersonalizationStateInfoCollection
        totalRecords = 0
        Try
            CheckSchemaVersion()
            Dim AllUsersScope As Boolean = True
            Dim returnValue As Integer
            Dim result As New Generic.List(Of Common.DbDataRecord)
            result = PersonalizationAdministration_FindState(True, pageIndex, pageSize, path, String.Empty, Nothing, returnValue)
            Dim sharedStateInfoCollection As PersonalizationStateInfoCollection = New PersonalizationStateInfoCollection
            If result.Count > 0 Then
                For Each reader As Common.DbDataRecord In result
                    Dim returnedPath As String = reader.GetString(0)
                    Dim lastUpdatedDate As DateTime = reader.GetDateTime(1)
                    Dim size As Integer = reader.GetInt64(2)
                    Dim userDataSize As Integer = reader.GetInt64(3)
                    Dim userCount As Integer = reader.GetInt64(4)
                    sharedStateInfoCollection.Add(New SharedPersonalizationStateInfo(returnedPath, lastUpdatedDate, size, userDataSize, userCount))
                Next
            End If
            ' Set the total count at the end after all operations pass
            If (Not returnValue = Nothing) Then
                totalRecords = CType(returnValue, Integer)
            End If
            Return sharedStateInfoCollection
        Catch Ex As System.Exception
            Throw
        End Try
    End Function

    Public Overrides Function FindState(ByVal scope As PersonalizationScope, ByVal query As PersonalizationStateQuery, ByVal pageIndex As Integer, ByVal pageSize As Integer, ByRef totalRecords As Integer) As PersonalizationStateInfoCollection
        PersonalizationProviderHelper.CheckPersonalizationScope(scope)
        PersonalizationProviderHelper.CheckPageIndexAndSize(pageIndex, pageSize)
        If (scope = PersonalizationScope.Shared) Then
            Dim pathToMatch As String = Nothing
            If (Not (query) Is Nothing) Then
                pathToMatch = CheckAndTrimString(query.PathToMatch, "query.PathToMatch", False, maxStringLength)
            End If
            Return FindSharedState(pathToMatch, pageIndex, pageSize, totalRecords)
        Else
            Dim pathToMatch As String = Nothing
            Dim inactiveSinceDate As DateTime = DefaultInactiveSinceDate
            Dim usernameToMatch As String = Nothing
            If (Not (query) Is Nothing) Then
                pathToMatch = CheckAndTrimString(query.PathToMatch, "query.PathToMatch", False, maxStringLength)
                inactiveSinceDate = query.UserInactiveSinceDate
                usernameToMatch = CheckAndTrimString(query.UsernameToMatch, "query.UsernameToMatch", False, maxStringLength)
            End If
            Return FindUserState(pathToMatch, inactiveSinceDate, usernameToMatch, pageIndex, pageSize, totalRecords)
        End If
    End Function

    Private Function FindUserState(ByVal path As String, ByVal inactiveSinceDate As DateTime, ByVal username As String, ByVal pageIndex As Integer, ByVal pageSize As Integer, ByRef totalRecords As Integer) As PersonalizationStateInfoCollection
        Dim result As New Generic.List(Of Common.DbDataRecord)
        totalRecords = 0
        Try
            CheckSchemaVersion()
            result = PersonalizationAdministration_FindState(False, pageIndex, pageSize, path, username, inactiveSinceDate, totalRecords)
            Dim stateInfoCollection As PersonalizationStateInfoCollection = New PersonalizationStateInfoCollection

            For Each reader As Common.DbDataRecord In result
                Dim returnedPath As String = reader.GetString(0)
                Dim lastUpdatedDate As DateTime = DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc)
                Dim size As Integer = reader.GetInt32(2)
                Dim returnedUsername As String = reader.GetString(3)
                Dim lastActivityDate As DateTime = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc)
                stateInfoCollection.Add(New UserPersonalizationStateInfo(returnedPath, lastUpdatedDate, size, returnedUsername, lastActivityDate))
            Next
            Return stateInfoCollection
        Catch Ex As System.Exception
            Throw
        End Try
    End Function

    Private Function GetCountOfSharedState(ByVal path As String) As Integer
        Dim count As Integer = 0
        Try
            CheckSchemaVersion()
            PersonalizationAdministration_GetCountOfState(True, path, String.Empty, DateTime.MinValue, count)
        Catch Ex As System.Exception
            Throw
        End Try
        Return count
    End Function

    Public Overrides Function GetCountOfState(ByVal scope As PersonalizationScope, ByVal query As PersonalizationStateQuery) As Integer
        PersonalizationProviderHelper.CheckPersonalizationScope(scope)
        If (scope = PersonalizationScope.Shared) Then
            Dim pathToMatch As String = Nothing
            If (Not (query) Is Nothing) Then
                pathToMatch = CheckAndTrimString(query.PathToMatch, "query.PathToMatch", False, maxStringLength)
            End If
            Return GetCountOfSharedState(pathToMatch)
        Else
            Dim pathToMatch As String = Nothing
            Dim userInactiveSinceDate As DateTime = DefaultInactiveSinceDate
            Dim usernameToMatch As String = Nothing
            If (Not (query) Is Nothing) Then
                pathToMatch = CheckAndTrimString(query.PathToMatch, "query.PathToMatch", False, maxStringLength)
                userInactiveSinceDate = query.UserInactiveSinceDate
                usernameToMatch = CheckAndTrimString(query.UsernameToMatch, "query.UsernameToMatch", False, maxStringLength)
            End If
            Return GetCountOfUserState(pathToMatch, userInactiveSinceDate, usernameToMatch)
        End If
    End Function

    Private Function GetCountOfUserState(ByVal path As String, ByVal inactiveSinceDate As DateTime, ByVal username As String) As Integer
        Dim count As Integer = 0
        Try
            CheckSchemaVersion()
            PersonalizationAdministration_GetCountOfState(False, path, username, inactiveSinceDate.ToUniversalTime, count)
        Catch Ex As System.Exception
            Throw
        End Try
        Return count
    End Function

    Public Overrides Sub Initialize(ByVal name As String, ByVal configSettings As NameValueCollection)
        If (configSettings Is Nothing) Then
            Throw New ArgumentNullException("configSettings")
        End If

        If String.IsNullOrEmpty(configSettings("dataProviderGroup")) Then
            Throw New HttpException("You must provide a dataProviderGroup")
        Else
            Dim DataProviderGroup As KDESolutions.Providers.DataProvider.DataProviderConfiguration = _
            CType(ConfigurationManager.GetSection(configSettings("dataProviderGroup")), KDESolutions.Providers.DataProvider.DataProviderConfiguration)
            If String.IsNullOrEmpty(DataProviderGroup.DBType) = False Then
                _DBType = DataProviderGroup.DBType
                Me.MyDBType = DataProviderGroup.DBType
            End If
            If String.IsNullOrEmpty(DataProviderGroup.DBServer) = False Then
                _DBServer = DataProviderGroup.DBServer
            End If
            If String.IsNullOrEmpty(DataProviderGroup.DBUser) = False Then
                _DBUser = DataProviderGroup.DBUser
            End If
            If String.IsNullOrEmpty(DataProviderGroup.DBPassword) = False Then
                _DBPassword = DataProviderGroup.DBPassword
            End If
            If String.IsNullOrEmpty(DataProviderGroup.DBDatabaseName) = False Then
                _DBDatabaseName = DataProviderGroup.DBDatabaseName
            End If
            If String.IsNullOrEmpty(DataProviderGroup.ConnectString) = False Then
                _ConnectString = DataProviderGroup.ConnectString
            End If
        End If

        If String.IsNullOrEmpty(name) Then
            name = "DBPersonalizationProvider"
        End If
        ' description will be set from the base class' Initialize method
        If String.IsNullOrEmpty(configSettings("description")) Then
            configSettings.Remove("description")
            configSettings.Add("description", "DBPersonalizationProvider")
        End If
        MyBase.Initialize(name, configSettings)
        _SchemaVersionCheck = 0
        ' If not available, the default value is set in the get accessor of ApplicationName
        _applicationName = configSettings("applicationName")
        If (Not (_applicationName) Is Nothing) Then
            configSettings.Remove("applicationName")
            If (_applicationName.Length > maxStringLength) Then
                Throw New ProviderException("PersonalizationProvider ApplicationNameExceedMaxLength, " & maxStringLength.ToString(CultureInfo.CurrentCulture))
            End If
        End If
        _TablePrefix = GetConfigValue(configSettings("tablePrefix"), "aspnet")
        _AppId = GetAppId()
        configSettings.Remove("applicationName")
        configSettings.Remove("description")
        configSettings.Remove("commandTimeout")
        configSettings.Remove("productKey")
        configSettings.Remove("activationDate")
        configSettings.Remove("dataProviderGroup")
        configSettings.Remove("tablePrefix")
        If (configSettings.Count > 0) Then
            Dim invalidAttributeName As String = configSettings.GetKey(0)
            Throw New ProviderException("PersonalizationProvider Unknown Property, invalidAttributeName, " & name)
        End If
    End Sub

    Private Function GetConfigValue(ByVal configValue As String, ByVal defaultValue As String) As String
        If String.IsNullOrEmpty(configValue) Then
            Return defaultValue
        End If
        Return configValue
    End Function

    Private Function LoadPersonalizationBlob(ByVal path As String, ByVal userName As String) As Byte()
        Dim result As New Generic.List(Of Common.DbDataRecord)
        Dim count As Integer
        If (Not (userName) Is Nothing) Then
            result = PersonalizationPerUser_GetPageSettings(userName, path, DateTime.UtcNow, count)
        Else
            result = PersonalizationAllUsers_GetPageSettings(path, count)
        End If
        If Not result Is Nothing Then
            For Each reader As Common.DbDataRecord In result
                Dim length As Integer = CType(reader.GetBytes(0, 0, Nothing, 0, 0), Integer)
                Dim state() As Byte = New Byte((length) - 1) {}
                reader.GetBytes(0, 0, state, 0, length)
                Return state
            Next
        Else
            Return Nothing
        End If
    End Function

    Protected Overrides Sub LoadPersonalizationBlobs(ByVal webPartManager As WebPartManager, ByVal path As String, ByVal userName As String, ByRef sharedDataBlob() As Byte, ByRef userDataBlob() As Byte)
        sharedDataBlob = Nothing
        userDataBlob = Nothing
        Try
            CheckSchemaVersion()
            sharedDataBlob = LoadPersonalizationBlob(path, Nothing)
            If Not String.IsNullOrEmpty(userName) Then
                userDataBlob = LoadPersonalizationBlob(path, userName)
            End If
        Catch Ex As System.Exception
            Throw
        End Try
    End Sub

    Private Sub ResetPersonalizationState(ByVal path As String, ByVal userName As String)
        If (Not (userName) Is Nothing) Then
            PersonalizationPerUser_ResetPageSettings(path, userName, DateTime.UtcNow)
        Else
            PersonalizationAllUsers_ResetPageSettings(path, userName, DateTime.UtcNow)
        End If
    End Sub

    Protected Overrides Sub ResetPersonalizationBlob(ByVal webPartManager As WebPartManager, ByVal path As String, ByVal userName As String)
        Try
            CheckSchemaVersion()
            ResetPersonalizationState(path, userName)
        Catch Ex As System.Exception
            Throw
        End Try
    End Sub

    Private Function ResetAllState(ByVal scope As PersonalizationScope) As Integer
        Dim count As Integer = 0
        Try
            CheckSchemaVersion()
            PersonalizationAdministration_DeleteAllState((scope = PersonalizationScope.Shared), count)
        Catch Ex As System.Exception
            Throw
        End Try
        Return count
    End Function

    Private Function ResetSharedState(ByVal paths() As String) As Integer
        Dim resultCount As Integer = 0
        Dim count As Integer = 0
        If (paths Is Nothing) Then
            resultCount = ResetAllState(PersonalizationScope.Shared)
        Else
            CheckSchemaVersion()
            For Each path As String In paths
                PersonalizationAdministration_ResetSharedState(count, path)
                resultCount = (resultCount + count)
            Next
        End If
        Return resultCount
    End Function

    Public Overloads Overrides Function ResetUserState(ByVal path As String, ByVal userInactiveSinceDate As DateTime) As Integer
        path = CheckAndTrimString(path, "path", False, maxStringLength)
        Dim paths() As String = Nothing
        Return ResetUserState(ResetUserStateMode.PerInactiveDate, userInactiveSinceDate, paths, Nothing)
    End Function

    Public Overrides Function ResetState(ByVal scope As PersonalizationScope, ByVal paths() As String, ByVal usernames() As String) As Integer
        PersonalizationProviderHelper.CheckPersonalizationScope(scope)
        paths = PersonalizationProviderHelper.CheckAndTrimNonEmptyStringEntries(paths, "paths", False, False, maxStringLength)
        usernames = PersonalizationProviderHelper.CheckAndTrimNonEmptyStringEntries(usernames, "usernames", False, True, maxStringLength)
        If (scope = PersonalizationScope.Shared) Then
            PersonalizationProviderHelper.CheckUsernamesInSharedScope(usernames)
            Return ResetSharedState(paths)
        Else
            PersonalizationProviderHelper.CheckOnlyOnePathWithUsers(paths, usernames)
            Return ResetUserState(paths, usernames)
        End If
    End Function

    Private Overloads Function ResetUserState(ByVal paths() As String, ByVal usernames() As String) As Integer
        Dim count As Integer = 0
        Dim hasPaths As Boolean = Not ((paths Is Nothing) _
                    OrElse (paths.Length = 0))
        Dim hasUsernames As Boolean = Not ((usernames Is Nothing) _
                    OrElse (usernames.Length = 0))
        If (Not hasPaths _
                    AndAlso Not hasUsernames) Then
            count = ResetAllState(PersonalizationScope.User)
        ElseIf Not hasUsernames Then
            count = ResetUserState(ResetUserStateMode.PerPaths, DefaultInactiveSinceDate, paths, usernames)
        Else
            count = ResetUserState(ResetUserStateMode.PerUsers, DefaultInactiveSinceDate, paths, usernames)
        End If
        Return count
    End Function

    Private Overloads Function ResetUserState(ByVal mode As ResetUserStateMode, ByVal userInactiveSinceDate As DateTime, ByVal paths() As String, ByVal usernames() As String) As Integer
        Dim count As Integer = 0
        Dim tempCount As Integer = 0
        Dim InactiveSinceDate As DateTime
        Try
            CheckSchemaVersion()
            Dim firstPath As String = ((Not (paths) Is Nothing) _
                        AndAlso (paths.Length > 0))
            If (mode = ResetUserStateMode.PerInactiveDate) Then
                If (userInactiveSinceDate <> DefaultInactiveSinceDate) Then
                    InactiveSinceDate = userInactiveSinceDate.ToUniversalTime
                End If
                PersonalizationAdministration_ResetUserState(InactiveSinceDate, "", "", count)
                tempCount = tempCount + count
            ElseIf (mode = ResetUserStateMode.PerPaths) Then
                For Each path As String In paths
                    PersonalizationAdministration_ResetUserState(InactiveSinceDate, "", path, count)
                    tempCount = tempCount + count
                Next
            Else
                For Each user As String In usernames
                    PersonalizationAdministration_ResetUserState(InactiveSinceDate, user, firstPath, count)
                    tempCount = tempCount + count
                Next
            End If
        Catch Ex As System.Exception
            Throw
        End Try
        Return tempCount
    End Function

    ''' <devdoc>
    ''' </devdoc>
    Private Sub SavePersonalizationState(ByVal path As String, ByVal userName As String, ByVal state() As Byte)
        Dim status As Integer
        If (Not (userName) Is Nothing) Then
            PersonalizationPerUser_SetPageSettings(userName, path, state, DateTime.UtcNow, status)
        Else
            PersonalizationAllUsers_SetPageSettings(path, state, DateTime.UtcNow)
        End If
    End Sub

    ''' <internalonly />
    Protected Overrides Sub SavePersonalizationBlob(ByVal webPartManager As WebPartManager, ByVal path As String, ByVal userName As String, ByVal dataBlob() As Byte)
        Try
            CheckSchemaVersion()
            SavePersonalizationState(path, userName, dataBlob)
        Catch Ex As System.Exception
            Throw
        End Try
    End Sub

    Friend Overloads Shared Function CheckAndTrimString(ByVal paramValue As String, ByVal paramName As String) As String
        Return CheckAndTrimString(paramValue, paramName, True)
    End Function

    Friend Overloads Shared Function CheckAndTrimString(ByVal paramValue As String, ByVal paramName As String, ByVal throwIfNull As Boolean) As String
        Return CheckAndTrimString(paramValue, paramName, throwIfNull, -1)
    End Function

    Friend Overloads Shared Function CheckAndTrimString(ByVal paramValue As String, ByVal paramName As String, ByVal throwIfNull As Boolean, ByVal lengthToCheck As Integer) As String
        If (paramValue Is Nothing) Then
            If throwIfNull Then
                Throw New ArgumentNullException(paramName)
            End If
            Return Nothing
        End If
        Dim trimmedValue As String = paramValue.Trim
        If (trimmedValue.Length = 0) Then
            Throw New ArgumentException("PersonalizationProvider Helper Trimmed Empty String, " & paramName)
        End If
        If ((lengthToCheck > -1) _
                    AndAlso (trimmedValue.Length > lengthToCheck)) Then
            Throw New ArgumentException("StringUtil Trimmed String Exceed Maximum Length, " & paramValue & ", " & paramName & ", " & lengthToCheck.ToString(CultureInfo.InvariantCulture))
        End If
        Return trimmedValue
    End Function

    Private Enum ResetUserStateMode
        PerInactiveDate
        PerPaths
        PerUsers
    End Enum
#Region "Private Helper methods"
    Private Shared Function GetDefaultAppName() As String
        Try
            Dim appName As String = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath
            If String.IsNullOrEmpty(appName) Then
                appName = System.Diagnostics.Process.GetCurrentProcess.MainModule.ModuleName
                Dim indexOfDot As Integer = appName.IndexOf(ChrW(46))
                If (indexOfDot <> -1) Then
                    appName = appName.Remove(indexOfDot)
                End If
            End If
            If String.IsNullOrEmpty(appName) Then
                Return "/"
            Else
                Return appName
            End If
        Catch Ex As System.Exception
            Return "/"
        End Try
    End Function

    Private Function GetAppId() As String
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        'Check to see if the application exists
        Dim sSQL As String = "SELECT  ApplicationId FROM " & _TablePrefix & "_Applications WHERE LoweredApplicationName = ?"
        DAP.AddParameter("@ApplicationName", _applicationName, DbType.String)
        _AppId = DAP.ExecuteScalar(sSQL)
        'If it doesn't insert a new application into the _Applications table

        If String.IsNullOrEmpty(_AppId) Then
            Dim sNewAppId As String = System.Guid.NewGuid.ToString
            sSQL = "INSERT INTO " & _TablePrefix & "_Applications(ApplicationId, ApplicationName, LoweredApplicationName) " & _
            "VALUES(?, ?, ?)"
            DAP.AddParameter("@ApplicationId", sNewAppId, DbType.String)
            DAP.AddParameter("@ApplicationName", _applicationName, DbType.String)
            DAP.AddParameter("@LoweredApplicationName", _applicationName.ToLower, DbType.String)
            If DAP.ExecuteNonQuery(sSQL) = 1 Then
                _AppId = sNewAppId
            Else
                _AppId = Nothing
            End If
        End If
        Return _AppId
    End Function

    Private Sub CheckSchemaVersion()
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Dim features(0) As String
        features(0) = "Personalization"

        Dim version As String = "1"
        If (features Is Nothing) Then
            Throw New ArgumentNullException("features")
        End If
        If (version Is Nothing) Then
            Throw New ArgumentNullException("version")
        End If
        Dim iStatus As Integer = 0
        For Each feature As String In features
            Dim sSQL As String = "SELECT COUNT(*) As SqlCount " & _
            "FROM " & _TablePrefix & "_SchemaVersions " & _
            "WHERE Feature = ? " & _
            "AND CompatibleSchemaVersion = ?"
            DAP.AddParameter("@Feature", feature, DbType.String)
            DAP.AddParameter("@CompatibleSchemaVersion", version, DbType.Int16)
            iStatus = DAP.ExecuteScalar(sSQL)
            If (iStatus = 0) Then
                _SchemaVersionCheck = -1
                Throw New ProviderException("Provider Schema Version Not Match " & MyBase.ToString & " version")
            End If
        Next
        If (_SchemaVersionCheck = -1) Then
            Throw New ProviderException("Provider Schema Version Not Match " & MyBase.ToString & " " & version)
        ElseIf (_SchemaVersionCheck = 0) Then
            If (_SchemaVersionCheck = -1) Then
                Throw New ProviderException("Provider Schema Version Not Match " & MyBase.ToString & " " & version)
            ElseIf (_SchemaVersionCheck = 0) Then
                _SchemaVersionCheck = 1
            End If
        End If
        DAP.Dispose()
    End Sub
#End Region

#Region "Converted Procedures"
    Private Function PersonalizationAdministration_FindState(ByVal AllUsersScope As Boolean, _
    ByVal PageIndex As Integer, ByVal PageSize As Integer, ByVal Path As String, ByVal Username As String, _
    ByVal InactiveSinceDate As DateTime, ByRef UserCount As Integer) As Generic.List(Of Common.DbDataRecord)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim PageLowerBound As Integer = PageSize * PageIndex
            Dim PageUpperBound As Integer = (PageSize - 1) + PageLowerBound
            Dim TotalRecords As Integer = 0
            Dim resultAllUsers As Generic.List(Of Common.DbDataRecord) = Nothing
            Dim sSQL As String
            If AllUsersScope Then
                'Start by getting the Ids for AllUsers Personalization
                sSQL = "SELECT Paths.PathId, Paths.LastUpdatedDate, " & _
                "PageSettings " & _
                "FROM " & _TablePrefix & "_PersonalizationAllUsers AllUsers, " & _
                _TablePrefix & "_Paths Paths " & _
                "WHERE Paths.ApplicationId = ? " & _
                "AND AllUsers.PathId = Paths.PathId " & _
                "AND (Paths.LoweredPath IS NULL OR Paths.LoweredPath = ?) " & _
                "ORDER BY Paths.Path ASC"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
                resultAllUsers = DAP.ExecuteReader(sSQL)
            End If
            Dim resultPerUser As Generic.List(Of Common.DbDataRecord)
            'Next get the PerUser Personalization
            sSQL = "SELECT PerUser.Id Paths.LastUpdatedDate, " & _
            "PageSettings " & _
            "FROM " & _TablePrefix & "_PersonalizationPerUser PerUser, " & _
            _TablePrefix & "_Users Users, " & _TablePrefix & "_Paths Paths " & _
            "WHERE Paths.ApplicationId = @ApplicationId " & _
            "AND PerUser.UserId = Users.UserId " & _
            "AND PerUser.PathId = Paths.PathId " & _
            "AND (Paths.LoweredPath IS NULL OR Paths.LoweredPath = ?) " & _
            "AND (Users.UserName IS NULL OR Users.LoweredUserName = ?) " & _
            "AND (Users.LastActivityDate <= ?) " & _
            "ORDER BY Paths.Path ASC, Users.UserName ASC"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            'Now combine the results
            If Not resultAllUsers Is Nothing Then
                resultPerUser = DAP.ExecuteReader(sSQL)
                For Each readerPerUser As Common.DbDataRecord In resultPerUser
                    resultAllUsers.Add(readerPerUser)
                Next
            Else
                resultAllUsers = DAP.ExecuteReader(sSQL)
            End If
            Dim returnValue As New Generic.List(Of Common.DbDataRecord)
            Dim i As Integer = 0
            For Each returnItem As Common.DbDataRecord In returnValue
                If i >= PageLowerBound AndAlso i <= PageUpperBound Then
                    returnValue.Add(resultAllUsers(i))
                End If
                i = (i + 1)
            Next
            UserCount = returnValue.Count
            Return returnValue
        Finally
            DAP.Dispose()
        End Try
    End Function

    Private Function GetCountOfSharedState(ByVal AllUsersScope As Boolean, ByVal Path As String, ByVal Username As String, _
    ByVal InactiveSinceDate As DateTime) As Integer
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim result As Integer
            Dim sSQL As String
            If AllUsersScope Then
                sSQL = "SELECT COUNT(*) " & _
"FROM " & _TablePrefix & "_PersonalizationAllUsers AllUsers, " & _
_TablePrefix & "_Paths Paths " & _
"WHERE Paths.ApplicationId = @ApplicationId " & _
"AND AllUsers.PathId = Paths.PathId " & _
"AND (Paths.LoweredPathPath IS NULL OR Paths.LoweredPath = ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
                result = DAP.ExecuteScalar(sSQL)
            Else
                sSQL = "SELECT COUNT(*) " & _
                "FROM " & _TablePrefix & "_PersonalizationPerUser PerUser, " & _
                _TablePrefix & "_Users Users, " & _TablePrefix & "_Paths Paths " & _
                "WHERE Paths.ApplicationId = @ApplicationId " & _
                "AND PerUser.UserId = Users.UserId " & _
                "AND PerUser.PathId = Paths.PathId " & _
                "AND (Paths.LoweredPath IS NULL OR Paths.LoweredPath = ?) " & _
                "AND (Users.LoweredUserName IS NULL OR Users.LoweredUserName = ?) " & _
                "AND (Users.LastActivityDate IS NULL OR Users.LastActivityDate <= ?) "
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@Path", Path.ToLower, DbType.String)
                DAP.AddParameter("@UserName", Username.ToLower, DbType.String)
                DAP.AddParameter("@InactiveSinceDate", InactiveSinceDate, DbType.DateTime)
                result = DAP.ExecuteScalar(sSQL)
            End If
            Return result
        Finally
            DAP.Dispose()
        End Try
    End Function

    Private Function PersonalizationPerUser_GetPageSettings(ByVal Username As String, ByVal Path As String, _
    ByVal CurrentTimeUtc As DateTime, ByRef status As Integer) As Generic.List(Of Common.DbDataRecord)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim PathId As String = String.Empty
            Dim UserId As String = String.Empty
            Dim sSQL As String
            Dim result As Generic.List(Of Common.DbDataRecord)
            sSQL = "SELECT u.PathId FROM " & _TablePrefix & "_Paths u WHERE u.ApplicationId = ? AND u.LoweredPath = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            PathId = DAP.ExecuteScalar(sSQL)
            If String.IsNullOrEmpty(PathId) Then
                Return Nothing
            Else
                sSQL = "SELECT u.UserId FROM " & _TablePrefix & "_Users u WHERE u.ApplicationId = ? AND u.LoweredUserName = ?"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@LoweredUserName", Username.ToLower, DbType.String)
                UserId = DAP.ExecuteScalar(sSQL)
                If String.IsNullOrEmpty(UserId) Then
                    Return Nothing
                Else
                    sSQL = "UPDATE " & _TablePrefix & "_Users " & _
                    "SET LastActivityDate = ? " & _
                    "WHERE UserId = ?"
                    DAP.AddParameter("@LastActivityDate", CurrentTimeUtc, DbType.DateTime)
                    DAP.AddParameter("@UserId", UserId, DbType.String)
                    status = DAP.ExecuteNonQuery(sSQL)
                    If status = 0 Then
                        Return Nothing
                    Else
                        sSQL = "SELECT p.PageSettings FROM " & _TablePrefix & "_PersonalizationPerUser p WHERE p.PathId = ? AND p.UserId = ?"
                        DAP.AddParameter("@PathId", PathId, DbType.String)
                        DAP.AddParameter("@UserId", UserId, DbType.String)
                        result = DAP.ExecuteReader(sSQL)
                    End If
                End If
            End If
            Return result
        Finally
            DAP.Dispose()
        End Try
    End Function

    Private Sub PersonalizationAdministration_GetCountOfState(ByVal AllUsersScope As Boolean, ByVal Path As String, _
    ByVal username As String, ByVal InactiveSinceDate As DateTime, ByRef result As Integer)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            If AllUsersScope Then
                sSQL = "SELECT COUNT(*) " & _
                "FROM " & _TablePrefix & "_PersonalizationAllUsers AllUsers, " & _
                _TablePrefix & "_Paths Paths " & _
                "WHERE Paths.ApplicationId = ? " & _
                "AND AllUsers.PathId = Paths.PathId " & _
                "AND (Paths.LoweredPath IS NULL OR Paths.LoweredPath = ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
                result = DAP.ExecuteScalar(sSQL)
            Else
                sSQL = "SELECT COUNT(*) " & _
                "FROM " & _TablePrefix & "_PersonalizationPerUser PerUser, " & _
                _TablePrefix & "_Users Users, " & _TablePrefix & "_Paths Paths " & _
                "WHERE Paths.ApplicationId = ? " & _
                "AND PerUser.UserId = Users.UserId " & _
                "AND PerUser.PathId = Paths.PathId " & _
                "AND (Paths.LoweredPath IS NULL OR Paths.LoweredPath = ?) " & _
                "AND (Users.LoweredUserName IS NULL OR Users.LoweredUserName ?) " & _
                "AND (Users.LastActivityDate IS NULL OR Users.LastActivityDate <= ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
                DAP.AddParameter("@LoweredUserName", username.ToLower, DbType.String)
                DAP.AddParameter("@LastActivityDate", InactiveSinceDate, DbType.DateTime)
                result = DAP.ExecuteScalar(sSQL)
            End If
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Function PersonalizationAllUsers_GetPageSettings(ByVal path As String, ByRef Status As Integer) As Generic.List(Of Common.DbDataRecord)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            Dim PathId As String = String.Empty
            sSQL = "SELECT u.PathId FROM " & _TablePrefix & "_Paths u WHERE u.ApplicationId = ? AND u.LoweredPath = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", path.ToLower, DbType.String)
            PathId = DAP.ExecuteScalar(sSQL)
            If String.IsNullOrEmpty(PathId) = False Then
                sSQL = "SELECT p.PageSettings FROM " & _TablePrefix & "_PersonalizationAllUsers p WHERE p.PathId = ?"
                DAP.AddParameter("@PathId", PathId, DbType.String)
                Dim result As Generic.List(Of Common.DbDataRecord)
                result = DAP.ExecuteReader(sSQL)
                Return result
            Else
                Return Nothing
            End If
        Finally
            DAP.Dispose()
        End Try
    End Function

    Private Sub PersonalizationPerUser_ResetPageSettings(ByVal UserName As String, ByVal Path As String, ByVal CurrentTimeUtc As DateTime)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            Dim PathId As String = String.Empty
            Dim UserId As String = String.Empty
            sSQL = "SELECT u.PathId FROM " & _TablePrefix & "_Paths u WHERE u.ApplicationId = ? AND u.LoweredPath = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            PathId = DAP.ExecuteScalar(sSQL)

            sSQL = "SELECT u.UserId FROM " & _TablePrefix & "_Users u WHERE u.ApplicationId = ? AND u.LoweredUserName = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredUserName", UserName.ToLower, DbType.String)
            UserId = DAP.ExecuteScalar(sSQL)

            sSQL = "UPDATE " & _TablePrefix & "_Users " & _
            "SET LastActivityDate = ? " & _
            "WHERE UserId = ?"
            DAP.AddParameter("@LastActivityDate", CurrentTimeUtc, DbType.DateTime)
            DAP.AddParameter("@UserId", UserId, DbType.String)

            sSQL = "DELETE FROM " & _TablePrefix & "_PersonalizationPerUser WHERE PathId = ? AND UserId = ?"
            DAP.AddParameter("@PathId", PathId, DbType.String)
            DAP.AddParameter("@UserId", UserId, DbType.String)
            DAP.ExecuteNonQuery(sSQL)
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Sub PersonalizationAllUsers_ResetPageSettings(ByVal UserName As String, ByVal Path As String, ByVal CurrentTimeUtc As DateTime)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            Dim PathId As String = String.Empty
            sSQL = "SELECT u.PathId FROM " & _TablePrefix & "_Paths u WHERE u.ApplicationId = ? AND u.LoweredPath = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            PathId = DAP.ExecuteScalar(sSQL)

            sSQL = "DELETE FROM " & _TablePrefix & "_PersonalizationAllUsers WHERE PathId = ?"
            DAP.AddParameter("@PathId", PathId, DbType.String)
            DAP.ExecuteNonQuery(sSQL)
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Sub PersonalizationAdministration_DeleteAllState(ByVal AllUsersScope As Boolean, ByRef Count As Integer)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            If AllUsersScope Then
                sSQL = "DELETE FROM " & _TablePrefix & "_PersonalizationAllUsers " & _
                "WHERE PathId IN " & _
                "(SELECT Paths.PathId " & _
                "FROM " & _TablePrefix & "_Paths Paths " & _
                "WHERE Paths.ApplicationId = ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.ExecuteNonQuery(sSQL)
            Else
                sSQL = "DELETE FROM " & _TablePrefix & "_PersonalizationPerUser " & _
                "WHERE PathId IN " & _
                "(SELECT Paths.PathId " & _
                "FROM " & _TablePrefix & "_Paths Paths " & _
                "WHERE Paths.ApplicationId = ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.ExecuteNonQuery(sSQL)
            End If
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Sub PersonalizationAdministration_ResetSharedState(ByRef Count As Integer, ByVal Path As String)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String

            sSQL = "DELETE FROM " & _TablePrefix & "_PersonalizationAllUsers " & _
            "WHERE PathId IN " & _
            "(SELECT AllUsers.PathId " & _
            "FROM " & _TablePrefix & "_PersonalizationAllUsers AllUsers, " & _
            _TablePrefix & "_Paths Paths " & _
            "WHERE Paths.ApplicationId = ? " & _
            "AND AllUsers.PathId = Paths.PathId " & _
            "AND Paths.LoweredPath = ?)"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            Count = DAP.ExecuteNonQuery(sSQL)
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Sub PersonalizationPerUser_SetPageSettings(ByVal UserName As String, ByVal Path As String, ByVal PageSettings As Byte(), _
    ByVal CurrentTimeUtc As DateTime, ByRef status As Integer)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            Dim PathId As String = String.Empty
            Dim UserId As String = String.Empty
            sSQL = "SELECT u.PathId FROM " & _TablePrefix & "_Paths u WHERE u.ApplicationId = ? AND u.LoweredPath = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            PathId = DAP.ExecuteScalar(sSQL)
            If String.IsNullOrEmpty(PathId) Then
                PathId = Paths_CreatePath(Path, String.Empty)
            End If
            sSQL = "SELECT u.UserId FROM " & _TablePrefix & "_Users u WHERE u.ApplicationId = ? AND u.LoweredUserName = ?"
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredUserName", UserName.ToLower, DbType.String)
            UserId = DAP.ExecuteScalar(sSQL)
            If String.IsNullOrEmpty(UserId) Then
                Dim newUserId As String = System.Guid.NewGuid.ToString
                sSQL = "INSERT INTO " & _TablePrefix & "_Users(ApplicationId, UserId, UserName, " & _
                "LoweredUserName, IsAnonymous, LastActivityDate) " & _
                "VALUES(?, ?, ?, ?, ?, ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@UserId", newUserId, DbType.String)
                DAP.AddParameter("@UserName", UserName, DbType.String)
                DAP.AddParameter("@LoweredUserName", UserName.ToLower, DbType.String)
                DAP.AddParameter("@IsAnonymous", 1, DbType.Int16)
                DAP.AddParameter("@LastActivityDate", DateTime.UtcNow, DbType.DateTime)
                If DAP.ExecuteNonQuery(sSQL) = 1 Then
                    UserId = newUserId
                End If
            End If
            sSQL = "UPDATE " & _TablePrefix & "_Users " & _
            "SET LastActivityDate = ? " & _
            "WHERE UserId = ?"
            DAP.AddParameter("@LastActivityDate", CurrentTimeUtc, DbType.DateTime)
            DAP.AddParameter("@UserId", UserId, DbType.String)
            DAP.ExecuteNonQuery(sSQL)
            Dim resultCount As Integer = 0
            sSQL = "SELECT Count(*) FROM " & _TablePrefix & "_PersonalizationPerUser WHERE UserId = ? AND PathId = ?"
            DAP.AddParameter("@UserId", UserId, DbType.String)
            DAP.AddParameter("@PathId", PathId, DbType.String)
            resultCount = DAP.ExecuteScalar(sSQL)
            If resultCount = 0 Then
                Dim Id As String = System.Guid.NewGuid.ToString
                sSQL = "INSERT INTO " & _TablePrefix & "_PersonalizationPerUser(Id, UserId, PathId, PageSettings, LastUpdatedDate) " & _
                "VALUES(?, ?, ?, ?, ?)"
                DAP.AddParameter("@Id", Id, DbType.String)
                DAP.AddParameter("@UserId", UserId, DbType.String)
                DAP.AddParameter("@PathId", PathId, DbType.String)
                DAP.AddParameter("@PageSettings", PageSettings, DbType.Binary)
                DAP.AddParameter("@LastUpdatedDate", CurrentTimeUtc, DbType.DateTime)
                DAP.ExecuteNonQuery(sSQL)
            Else
                sSQL = "UPDATE " & _TablePrefix & "_PersonalizationPerUser SET PageSettings = ?, " & _
                "LastUpdatedDate = ? " & _
                "WHERE UserId = ? AND PathId = ?"
                DAP.AddParameter("@PageSettings", PageSettings, DbType.Binary)
                DAP.AddParameter("@LastUpdatedDate", CurrentTimeUtc, DbType.DateTime)
                DAP.AddParameter("@UserId", UserId, DbType.String)
                DAP.AddParameter("@PathId", PathId, DbType.String)
                DAP.ExecuteNonQuery(sSQL)
            End If
            status = 0
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Function Paths_CreatePath(ByVal Path As String, ByVal PathId As String) As String
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Dim returnString As String = String.Empty
        Try
            Dim sSQL As String
            Dim resultCount As Integer = 0
            sSQL = "SELECT COUNT(*) As ResultCount FROM " & _TablePrefix & "_Paths WHERE LoweredPath = ? AND ApplicationId = ?"
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
            resultCount = DAP.ExecuteScalar(sSQL)
            If resultCount = 0 Then
                Dim newPathId As String = System.Guid.NewGuid.ToString
                sSQL = "INSERT INTO " & _TablePrefix & "_Paths(ApplicationId, Path, LoweredPath, PathId) VALUES(?, ?, ?, ?)"
                DAP.AddParameter("@ApplicationId", _AppId, DbType.String)
                DAP.AddParameter("@Path", Path, DbType.String)
                DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
                DAP.AddParameter("@PathId", newPathId, DbType.String)
                DAP.ExecuteNonQuery(sSQL)
            End If
            sSQL = "SELECT PathId FROM " & _TablePrefix & "_Paths WHERE LoweredPath = ? AND ApplicationId = ?"
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            DAP.AddParameter("@Appliationid", _AppId, DbType.String)
            returnString = DAP.ExecuteScalar(sSQL)
            Return returnString
        Finally
            DAP.Dispose()
        End Try
    End Function

    Private Sub PersonalizationAllUsers_SetPageSettings(ByVal Path As String, ByVal PageSettings As Byte(), ByVal CurrentDateTime As DateTime)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String
            Dim PathId As String = String.Empty
            sSQL = "SELECT u.PathId FROM " & _TablePrefix & "_Paths u WHERE u.ApplicationId = ? AND u.LoweredPath = ?"
            DAP.AddParameter("@ApplicatinId", _AppId, DbType.String)
            DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            PathId = DAP.ExecuteScalar(sSQL)
            If String.IsNullOrEmpty(PathId) Then
                PathId = System.Guid.NewGuid.ToString
                Paths_CreatePath(Path, PathId)
            End If
            sSQL = "SELECT PathId FROM " & _TablePrefix & "_PersonalizationAllUsers WHERE PathId = ?)"
            DAP.AddParameter("@PathId", PathId, DbType.String)
            Dim resultCount As Integer = DAP.ExecuteNonQuery(sSQL)
            If resultCount > 0 Then
                sSQL = "UPDATE " & _TablePrefix & "_PersonalizationAllUsers SET PageSettings = ?, LastUpdatedDate = ? WHERE PathId = ?"
                DAP.AddParameter("@PageSettings", PageSettings, DbType.Binary)
                DAP.AddParameter("@LastUpdatedDate", CurrentDateTime, DbType.DateTime)
                DAP.AddParameter("@PathId", PathId, DbType.String)
                DAP.ExecuteNonQuery(sSQL)
            Else
                sSQL = "INSERT INTO " & _TablePrefix & "_PersonalizationAllUsers(PathId, PageSettings, LastUpdatedDate) VALUES (?, ?, ?)"
                DAP.AddParameter("@PathId", PathId, DbType.String)
                DAP.AddParameter("@PageSettings", PageSettings, DbType.Binary)
                DAP.AddParameter("@LastUpdatedDate", CurrentDateTime, DbType.Date)
                DAP.ExecuteNonQuery(sSQL)
            End If
        Finally
            DAP.Dispose()
        End Try
    End Sub

    Private Sub PersonalizationAdministration_ResetUserState(ByVal InactiveSinceDate As DateTime, ByVal Username As String, _
    ByVal Path As String, ByRef result As Integer)
        Dim DAP As New nsDataProvider.DataProvider(_DBType, _DBServer, _DBUser, _DBPassword, _DBDatabaseName, _ConnectString)
        Try
            Dim sSQL As String

            sSQL = "DELETE FROM " & _TablePrefix & "_PersonalizationPerUser " & _
            "WHERE Id IN (SELECT PerUser.Id " & _
            "FROM " & _TablePrefix & "_PersonalizationPerUser PerUser, " & _
            _TablePrefix & "_Users Users, " & _TablePrefix & "_Paths Paths " & _
            "WHERE Paths.ApplicationId = ? " & _
            "AND PerUser.UserId = Users.UserId " & _
            "AND PerUser.PathId = Paths.PathId "
            DAP.AddParameter("@AppicationId", _AppId, DbType.String)
            If InactiveSinceDate <> DateTime.MinValue.ToUniversalTime Then
                sSQL = sSQL & "AND (Users.LastActivityDate IS NULL OR Users.LastActivityDate <= ?) "
                DAP.AddParameter("@LastActivityDate", InactiveSinceDate, DbType.DateTime)
            End If
            If String.IsNullOrEmpty(Username) = False Then
                sSQL = sSQL & "AND (Users.LoweredUserName IS NULL OR Users.LoweredUserName = ?) "
                DAP.AddParameter("@LoweredUserName", Username.ToLower, DbType.String)
            End If
            If String.IsNullOrEmpty(Path) = False Then
                sSQL = "AND (Paths.LoweredPath OR Paths.LoweredPath = ?))"
                DAP.AddParameter("@LoweredPath", Path.ToLower, DbType.String)
            End If
            result = DAP.ExecuteNonQuery(sSQL)
        Finally
            DAP.Dispose()
        End Try
    End Sub
#End Region
End Class


